const util = require('../../../utils/util.js');
const api = require('../../../config/api.js');
const user = require('../../../services/user.js');
const { $Message } = require('../../../lib/iview/base/index');
const common = require('../../../utils/common.js');
const app = getApp();
Page({
  data: {
    circleid: "766",
    logininfo: {},
    openid: '',
    login_code: '',
    //上传面板
    openUpload: false,
    checkIdentityAndVIP: false,//检查是否通过身份认证和VIP
    preferentialOpenStoreDialogShow: false,// 免费开通店铺的弹窗
    openStoreInfo: {},// 开通店铺的信息
    addBabyselectCircle: false,//添加宝贝选择圈子面板
    interestJoinList: [],//用户创建的圈子
    selectCircle: null,//添加宝贝选中的圈子
  },
  //加载
  onLoad: function () {
    var _this = this
    if (app.globalData.logininfo.openid != '' && app.globalData.logininfo.openid!=null){
      _this.setData({
        logininfo: app.globalData.logininfo,
        openid: app.globalData.logininfo.openid
      });
      console.log(app.globalData.logininfo)
    }  
  },
  //
  onShow: function(){
    var _this = this
    if (app.globalData.logininfo.openid != '' && app.globalData.logininfo.openid != null) {
      _this.setData({
        logininfo: app.globalData.logininfo,
        openid: app.globalData.logininfo.openid
      });
      console.log(app.globalData.logininfo)
    }  
    app.switchData = 99999;
  },
  //拉伸顶部刷新
  onPullDownRefresh() {
    this.onLoad();
    wx.stopPullDownRefresh();
  },
  //打开上传面板
  showUpload: function () {
    var _this = this
    _this.setData({
      openUpload: true
    })
    wx.hideTabBar({
    })
  },
  //打开选择上传路径面板
  showUploadPop: function (e) {
    var _this = this
    wx.hideTabBar({
    })
    var type = e.currentTarget.dataset.type
    if (type == "img") {
      var str = [{ "title": "拍照", "type": "img" }, { "title": "从手机相册选择", "type": "img" }, { "title": "从微信导入图片", "type": "img" }]
      _this.setData({
        popText: str
      })
    }
    if (type == "video") {
      var str = [{ "title": "拍摄", "type": "video" }, { "title": "从手机相册选择", "type": "video" }, { "title": "从微信导入视频", "type": "video" }]
      _this.setData({
        popText: str
      })
    }
    this.setData({
      openUploadPop: true,
      openUpload: false
    })
  },
  //打开拍摄
  openShoot: function (e) {
    var _this = this
    var type = e.currentTarget.dataset.type
    if (type == "img") {
      var imgArr = []
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['camera'],
        success(res) {
          _this.closeMC();
          wx.navigateTo({
            url: '/ucenter/pages/ucenter/personinfo/avatar/index?atype=journeyImg&imageSrc=' + res.tempFilePaths[0],
          })
        }
      })
    }
    if (type == "video") {
      wx.chooseVideo({
        sourceType: ['camera'],
        maxDuration: util.getVideoFileMaxTime("diary"),
        camera: 'back',
        success(res) {
          _this.closeMC();
          var info = {};
          info.id = "myVideo" + new Date().getTime();
          info.size = res.size;
          info.path = res.tempFilePath;
          info.width = res.width;
          info.height = res.height;
          info.totalTime = res.duration;
          info.totalDate = util.digitalFormatTime(res.duration);
          wx.navigateTo({
            url: '/interest/pages/interest/makeImage/publishJourneyVideo/publishJourneyVideo?info=' + JSON.stringify(info),
          })
        }
      })
    }
  },
  //打开相册
  openAlbum: function (e) {
    var _this = this
    var type = e.currentTarget.dataset.type
    if (type == "img") {
      var imgArr = []
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        success(res) {
          _this.closeMC();
          wx.navigateTo({
            url: '/ucenter/pages/ucenter/personinfo/avatar/index?atype=journeyImg&imageSrc=' + res.tempFilePaths[0],
          })
        }
      })
    }
    if (type == "video") {
      wx.chooseVideo({
        sourceType: ['album'],
        maxDuration: util.getVideoFileMaxTime("diary"),
        camera: 'back',
        success(res) {
          _this.closeMC();
          var maxSize = util.getVideoFileMaxSize("diary");
          if ((res.size / 1024 / 1024) > maxSize) {
            util.dialogAlert("视频大小超出" + maxSize + "M");
            return;
          }
          var info = {};
          info.id = "myVideo" + new Date().getTime();
          info.size = res.size;
          info.path = res.tempFilePath;
          info.width = res.width;
          info.height = res.height;
          info.totalTime = res.duration;
          info.totalDate = util.digitalFormatTime(res.duration);
          wx.navigateTo({
            url: '/interest/pages/interest/makeImage/publishJourneyVideo/publishJourneyVideo?info=' + JSON.stringify(info),
          })
        }
      })
    }
  },
  //打开微信文件
  openWeChatFile: function (e) {
    var _this = this
    var type = e.currentTarget.dataset.type
    if (type == "img") {
      var imgArr = []
      wx.chooseMessageFile({
        count: 1,
        type: 'image',
        success(res) {
          _this.closeMC();
          wx.navigateTo({
            url: '/ucenter/pages/ucenter/personinfo/avatar/index?atype=journeyImg&imageSrc=' + res.tempFiles[0].path,
          })
        }
      })
    }
    if (type == "video") {
      wx.chooseMessageFile({
        count: 1,
        type: 'video',
        success(res) {
          var tempFiles = res.tempFiles[0];
          var maxSize = util.getVideoFileMaxSize("diary");
          if ((tempFiles.size / 1024 / 1024) > maxSize) {
            util.dialogAlert("视频大小超出" + maxSize + "M");
            return;
          }
          var info = {};
          info.id = "myVideo" + new Date().getTime();
          info.size = tempFiles.size;
          info.path = tempFiles.path;
          info.width = 0;
          info.height = 0;
          info.totalTime = 0;
          info.totalDate = "00:00";
          wx.navigateTo({
            url: '/interest/pages/interest/makeImage/publishJourneyVideo/publishJourneyVideo?info=' + JSON.stringify(info),
          })
        }
      })
    }
  },
  //关闭面板
  closeMC: function () {
    var _this = this
    _this.setData({
      openUpload: false,
      openUploadPop: false,
      preferentialOpenStoreDialogShow: false,
      checkIdentityAndVIP: false,
      addBabyselectCircle: false,
    })
    wx.showTabBar({
    })
  },
  //登陆
  doLogin: function (e) {
    var _this = this;
    common.doLogin(e,_this);
  },
  //进入成绩单
  gograde: function () {
    app.switchData = 1;
    wx.switchTab({
      url: '/pages/grade/grade',
    });
  },
  //添加一个新的兴趣圈子
  doPublish: function () {
    wx.navigateTo({
      url: '../../../ucenter/pages/ucenter/personcenter/publish/publish',
    })
  },
  //进入我的主页
  enterPerson: function () {
    wx.navigateTo({
      url: '../../../ucenter/pages/ucenter/personhome/personhome'
    })
  },
  //点击头像，进入编辑资料
  doAvatar: function () {
    var _this = this
    wx.navigateTo({
      url: '../../../ucenter/pages/ucenter/personinfo/personinfo',
    })
    _this.closeMC();
  },
  //跳转消息中心
  domessage: function () {
    wx.navigateTo({
      url: '../../chat/chat?userid=1',
    })
  },
  //跳转兴趣圈
  gotointerest: function(){
    wx.switchTab({
      url: '/pages/interest/interest',
    })
  },
  //跳转登陆
  gotologin: function(){
    wx.navigateTo({
      url: 'login/login',
    })
  },
  //跳转店铺
  gotoStore: function(){
    var _this = this
    app.switchData = '';
    wx.navigateTo({
      url: '../../../grade/pages/grade/myStore/myStore',
    })
  },
  /**
   * 检查是否开通店铺
   */
  circleDistribution: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var param = {};
        param.access_token = res.access_token;
        param.openid = openid;  
        util.post(api.My_checkUserOpenStoreApi, param).then(function (res2) {
          if (res2.code == 200) {
            var obj = res2.result.obj;
            // if (!obj.isOpen) {
            if (true) {
              // 未开通
              var openStorePrice = obj.openStorePrice;// 开通原价
              // var storePreferentialPrice = obj.storePreferentialPrice;
              // var preferentialPrice = storePreferentialPrice.preferentialPrice;// 开通优惠价格
              var openText = "";
              var openPrice = 0;
              var openType = 1;
              var residueStore = 9999;//剩余的免费名额
              if (residueStore<=10000) {
                openText = "免费";
                openType = 2;
                openPrice = 0;
              }else {
                openText = "优惠"; 
                openType = 1;
                openPrice = 0;
              }
              obj.openText = openText;
              obj.openPrice = openPrice;
              obj.openType = openType;
              _this.setData({
                openStoreInfo: obj,
                preferentialOpenStoreDialogShow: true
              })
              wx.hideTabBar({
              })
            } else {
              app.switchData = '';
              //进入店铺 圈子模块
              if (type == "circle") {
                app.switchData = 0;
              }
              //进入店铺 书包模块
              if (type == "read") {
                app.switchData = 1;
              }
              //进入店铺 专辑模块
              if (type == "album") {
                app.switchData = 2;
              }
              //进入店铺 宝贝模块
              if (type == "goods") {
                app.switchData = 3;
              }
              wx.navigateTo({
                url: '../../../grade/pages/grade/myStore/myStore',
              })
            }
          }
        })
      });
    }
  },
  /**
   * 开通店铺
   */
  preferentialOpenStoreDialogSuccess: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type
    if (type==2){
      _this.preferentialOpenStoreDialogClose();
      //判断是否有认证
      if(false){
        _this.setData({
          checkText: '',
        })
      }else{
        _this.setData({
          checkText: '（注：圈主晋级后，不要忘记做身份认证，否则无法体现您的收益哦！）',
        })
      }
      _this.setData({
        checkIdentityAndVIP: true,
      })
    }else{
      _this.gotoPromotedVIP();
    }
  },
  /**
  *  开通店铺弹窗关闭
  */
  preferentialOpenStoreDialogClose: function () {
    var _this = this;
    _this.setData({
      preferentialOpenStoreDialogShow: false,
      storeDialogShowIndex: "",
      openStoreInfo: {}
    })
  },
  //跳转设置
  gotoSetting: function () {
    wx.navigateTo({
      url: 'setting/setting',
    })
  },
  //跳转行程日历
  gotoJourney: function(){
    wx.navigateTo({
      url: '/grade/pages/grade/journey/journey',
    })
  },
  //授权手机号的弹窗
  getPhoneNumber: function (e) {
    var _this = this;
    wx.login({
      success: function (res) {
        var openid = app.globalData.logininfo.openid;
        var code = res.code;
        if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
          wx.showToast({
            title: '获取手机号失败',
            icon: 'none',
            duration: 2000
          })
        } else {
          // 同意授权
          var encryptedData = e.detail.encryptedData;
          var iv = e.detail.iv;
          util.post(api.fetchToken()).then(function (res) {
            if (res.access_token != '') {
              return Promise.resolve({
                access_token: res.access_token
              });
            }
          }).then(function (res) {
            var data = {};
            data.encryptedData = encryptedData;
            data.iv = iv;
            data.openid = openid;
            data.code = code;
            data.access_token = res.access_token;
            data.sessionkey = app.globalData.logininfo.sessionkey;
            util.post(api.Home_UpdateUserMobileApiUrl, data).then(function (res) {
              if (res.code == 200) {
                console.log(res)
              }
            })
          })
        }
      }
    });
  },
  /**
   * 新增宝贝
   */
  addBaby: function(){
    var _this = this
    var openid = app.globalData.logininfo.openid;
    var data = {};
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.selectOpenid = openid;
        data.access_token = res.access_token;
        util.post(api.Home_ParticipateCircleApiUrl, data).then(function (res2) {
          if (res2.code == 200) {
            var arr = []
            for (var i = 0; i < res2.result.list.length; i++) {
              if (res2.result.list[i].identityType == 1) {
                arr.push(res2.result.list[i])
              }
            }
            _this.setData({
              interestJoinList: arr,
              addBabyselectCircle: true
            })
            wx.hideTabBar({
            })
            console.log(arr)
          }
        })
      });
    }
  },
  /**
   * 选择添加宝贝绑定的圈子
   */
  clickCircle: function(e){
    var _this = this;
    var index = e.currentTarget.dataset.index
    _this.setData({
      selectCircle: index+1
    })
  },
  /**
   * 进入管理主题
   */
  gotoThemeManage: function(){
    var _this = this;
    var selectCircle = _this.data.selectCircle-1;
    var arr = _this.data.interestJoinList;
    var circleid = arr[selectCircle].circleid;
    wx.navigateTo({
      url: "/interest/pages/interest/theme/themManage/themManage?circleid=" + circleid
    })
    wx.showTabBar({
    })
  },
  /**
   * 进入订单中心
   */
  gotoOrderCenter: function () {
    wx.navigateTo({
      url: '/interest/pages/interest/orderCentre/orderCentre',
    })
  },
  /**
   * 跳转身份认证
   */
  gotoAuthentication: function () {
    wx.navigateTo({
      url: '/grade/pages/grade/authentication/authentication',
    })
  },
  /**
   * 跳转晋级VIP
   */
  gotoPromotedVIP: function () {
    wx.navigateTo({
      url: '/grade/pages/grade/promotedVIP/promotedVIP',
    })
  },
})